package com.sino.operation.config.persistence;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sino.operation.Exception.exceptionRoot.SinoException;
import com.sino.operation.config.Spring.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Introspector;
import java.io.Serializable;
import java.util.List;

/**
 * @Title: MyPersistence
 * @Description:
 * @Author dengls
 * @date 2021/10/12 17:30
 */
@Component
@Slf4j
public class MyPersistence<S extends ServiceImpl, T extends Serializable> {
    private S service;


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void save(List<T> data) {
        this.saveList(data);
    }

    public void saveList(List<T> data) {
        data.forEach(
                item -> {
                    this.saveData(item);
                }
        );
    }

    public void saveData(T data) {
        if (data instanceof List) {
            this.saveList((List<T>) data);
        } else {
            String serviceName = data.getClass().getSimpleName() + "ServiceImpl";
            serviceName = Introspector.decapitalize(serviceName);
            try {
                service = (S) SpringContextUtils.getBean(serviceName);
            } catch (Exception e) {
                log.info("未找到对应实体的服务类");
                throw new SinoException(500, "未找到对应实体的服务类，" + e.getMessage());
            }
            try {
                service.saveOrUpdate(data);
            } catch (Exception e) {
                log.info("数据持久化失败");
                throw new SinoException(500, "数据持久化失败，" + e.getMessage());
            }
        }

    }
}
